package com.nefu.huiyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nefu.huiyi.entity.MedicalCompany;
import com.nefu.huiyi.entity.MedicalCompanyPolicy;
import com.nefu.huiyi.exception.BusinessException;
import com.nefu.huiyi.mapper.IMedicalCompanyMapper;
import com.nefu.huiyi.mapper.IMedicalCompanyPolicyMapper;
import com.nefu.huiyi.service.IMedicalCompanyPolicyService;
import com.nefu.huiyi.service.IMedicalCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MedicalCompanyPolicyServiceImpl extends ServiceImpl<IMedicalCompanyPolicyMapper, MedicalCompanyPolicy> implements IMedicalCompanyPolicyService {
    // 继承ServiceImpl后，大部分通用业务方法已实现

//    @Autowired
//    private IMedicalCompanyService medicalCompanyService;
//
//    public boolean save(MedicalCompanyPolicy policy){
//        Long companyId = policy.getCompanyId();
//
//        if (companyId == null){
//            throw new BusinessException("公司ID不能为空");
//        }
//
//        if(medicalCompanyService.getById(companyId) == null){
//            throw new BusinessException("关联的医药公司不存在，无法新增政策");
//        }
//
//        // 如果公司存在，调用父类的原始save方法执行数据库插入
//        return super.save(policy);
//    }
    @Autowired
    private IMedicalCompanyMapper medicalCompanyMapper;

    @Autowired
    private IMedicalCompanyService medicalCompanyService;


    // 直接修改 Controller 调用的 page() 方法
    public Page<MedicalCompanyPolicy> getPolicyPageWithDetails(Page<MedicalCompanyPolicy> page, QueryWrapper<MedicalCompanyPolicy> queryWrapper) {
        // 先执行标准的分页查询，获取政策列表,此时返回的 records 中，companyName 字段是 null
        Page<MedicalCompanyPolicy> policyPage = this.page(page, queryWrapper);

        List<MedicalCompanyPolicy> policies = policyPage.getRecords();
        if (policies.isEmpty()) {
            return policyPage; // 如果没有数据，直接返回，避免后续无效查询
        }

        // 从政策列表中提取出所有不重复的 companyId
        List<Long> companyIds = policies.stream()
                .map(MedicalCompanyPolicy::getCompanyId)
                .distinct()
                .collect(Collectors.toList());

        // 查询出所有相关的公司信息
        List<MedicalCompany> companies = medicalCompanyService.listByIds(companyIds);

        // 将公司列表转换为 Map<id, name> 以便快速查找
        Map<Long, String> companyIdToNameMap = companies.stream()
                .collect(Collectors.toMap(MedicalCompany::getId, MedicalCompany::getCompanyName));

        // 遍历政策列表，将公司名称设置进去
        policies.forEach(policy -> {
            policy.setCompanyName(companyIdToNameMap.get(policy.getCompanyId()));
        });

        // 将处理过的 records 设置回 page 对象
        policyPage.setRecords(policies);

        return policyPage;
    }

}
